package com.boot.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boot.entity.Perm;
import com.boot.entity.User;
import com.boot.mapper.UserMapper;
import com.boot.service.IPermService;
import com.boot.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private IPermService permService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = lambdaQuery().eq(User::getUsername, username).one();
        if (user == null) {
            throw new UsernameNotFoundException("根据用户名找不到用户");
        }
        //找权限
        List<Perm> perms = permService.lambdaQuery().eq(Perm::getUserId, user.getId()).list();

        List<String> permTags = perms.stream().map(Perm::getTag).toList();
        if (!user.getPassword().startsWith("{")){
            user.setPassword("{noop}"+user.getPassword());
        }
        user.setAuthorities(AuthorityUtils.createAuthorityList(permTags));

        return user;
    }
}
